package com.department.mydepartment.service;

import com.department.mydepartment.entities.Article;
import com.department.mydepartment.repository.ArticleRepository;
import com.department.mydepartment.util.ShowData;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.mock.web.MockMultipartFile;
import org.apache.commons.io.IOUtils;

import javax.transaction.Transactional;
import java.io.*;
import java.sql.Timestamp;
import java.util.List;

@Service
public class ArticleService {

    @Autowired
    private UploadService uploadService;
    @Autowired
    ArticleRepository articleRepository;
    @Autowired
    ShowData showData;

    /**
     * 创建文章(有封面和无封面)
     * @param articleTitle
     * @param articleTag
     * @param articleType
     * @param content
     * @param img
     * @return
     */
    public String createWithCover(String articleTitle, String articleTag, String articleType, String content, MultipartFile img) {
        List<Article> isExist = articleRepository.findByArticleTitleAndArticleTagAndArticleType(
                articleTitle, articleTag, articleType);
        if (isExist.size() == 1) {
            return showData.showData(false, "文章已存在");
        }
        String imgUrl = uploadService.upload(img).get("fileName").toString();
        if ("".equals(imgUrl)) {
            return showData.showData(false, "创建失败");
        }
        String fileUrl = uploadMarkDown(content);
        if ("".equals(fileUrl)) {
            return showData.showData(false, "文章内容不能为空");
        }
        Timestamp timestamp = new Timestamp(System.currentTimeMillis());
        String timeString = timestamp.toString();
        timeString = timeString.split(" ")[0].split("-")[0] +
                timeString.split(" ")[0].split("-")[1] +
                timeString.split(" ")[0].split("-")[2] +
                timeString.split(" ")[1].split(":")[0] +
                timeString.split(" ")[1].split(":")[1] +
                timeString.split(" ")[1].split(":")[2].split("\\.")[0];
        Article article = new Article(timeString, articleTitle, articleTag, articleType, fileUrl, imgUrl, timestamp, timestamp);
        Article isSuccess = articleRepository.save(article);
        if (isSuccess == null) {
            return showData.showData(false, "创建失败");
        }
        return showData.showData(true, "创建成功");
    }

    public String createWithoutCover(String articleTitle, String articleTag, String articleType, String content) {
        List<Article> isExist = articleRepository.findByArticleTitleAndArticleTagAndArticleType(
                articleTitle, articleTag, articleType);
        if (isExist.size() == 1) {
            return showData.showData(false, "文章已存在");
        }
        String fileUrl = uploadMarkDown(content);
        if ("".equals(fileUrl)) {
            return showData.showData(false, "文章内容不能为空");
        }
//        Date dt = new Date();
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss");
//        String data = sdf.format(dt);
        Timestamp timestamp = new Timestamp(System.currentTimeMillis());
        String timeString = timestamp.toString();
        timeString = timeString.split(" ")[0].split("-")[0] +
                timeString.split(" ")[0].split("-")[1] +
                timeString.split(" ")[0].split("-")[2] +
                timeString.split(" ")[1].split(":")[0] +
                timeString.split(" ")[1].split(":")[1] +
                timeString.split(" ")[1].split(":")[2].split("\\.")[0];
        Article article = new Article(timeString, articleTitle, articleTag, articleType, fileUrl, timestamp, timestamp);
        Article isSuccess = articleRepository.save(article);
        if (isSuccess == null) {
            return showData.showData(false, "创建失败");
        }
        return showData.showData(true, "创建成功");
    }

    /**
     * 查询文章(通过id、标题、类型、标签)
     *
     * @return
     */
    public String findByArticleId(String articleId) {
        Article byArticleId = articleRepository.findByArticleId(articleId);
        if (byArticleId != null) {
            return showData.showData(true, byArticleId.toString());
        }
        return showData.showData(false, "查询失败");
    }

    public String findByArticleTitle(String articleTitle) {
        List<Article> byArticleTitle = articleRepository.findByArticleTitle(articleTitle);
        if (byArticleTitle.size() != 0) {
            return showData.showData(true, byArticleTitle.toString());
        }
        return showData.showData(false, "查询失败，无此文章！");
    }

    public String findByArticleTag(String articleTag) {
        List<Article> byArticleTag = articleRepository.findByArticleTag(articleTag);
        if (byArticleTag.size() != 0) {
            return showData.showData(true, byArticleTag.toString());
        }
        return showData.showData(false, "查询失败");
    }

    public String findByArticleType(String articleType) {
        List<Article> byArticleType = articleRepository.findByArticleType(articleType);
        if (byArticleType.size() != 0) {
            return showData.showData(true, byArticleType.toString());
        }
        return showData.showData(false, "查询失败");
    }

    /**
     * 编辑文章
     * @param articleId
     * @return
     */
    public String editByArticleId(String articleId, String articleTitle, String content) {
        Article byArticleId = articleRepository.findByArticleId(articleId);
        if (byArticleId != null) {
            byArticleId.setArticleTitle(articleTitle);
            String fileUrl = uploadMarkDown(content);
            byArticleId.setFileUrl(fileUrl);
            Timestamp timestamp = new Timestamp(System.currentTimeMillis());
            byArticleId.setUpdateTime(timestamp);
            articleRepository.save(byArticleId);
            return showData.showData(true, "修改成功");
        }
        return showData.showData(false, "文章不存在");
    }

    /**
     * 删除文章
     * 通过id删除
     * 和批量删除
     *
     * @param articleId
     * @return
     */
    @Transactional
    public String deleteByArticleId(String articleId) {
        Article byArticleId = articleRepository.findByArticleId(articleId);
        if (byArticleId != null) {
            articleRepository.deleteByArticleId(articleId);
            List<Article> allArticle = articleRepository.findAll();
            return showData.showData(true, allArticle.toString());
        }
        return showData.showData(false, "文章不存在");
    }

    @Transactional
    public String deleteArticleList(String[] articleIdList) {
        for (int i = 0; i < articleIdList.length; i++) {
            articleRepository.deleteByArticleId(articleIdList[i]);
        }
        List<Article> allArticle = articleRepository.findAll();
        return showData.showData(true, allArticle.toString());
    }

    /**
     * 获取文章内容、Id、toString
     *
     * @param articleId
     * @return
     * @throws IOException
     */
    public String getArticleContent(String articleId) throws IOException {
        Article byArticleId = articleRepository.findByArticleId(articleId);
        if (byArticleId != null) {
            String content = sendGetData(byArticleId.getFileUrl());
            return showData.showData(true, content);
        }
        return showData.showData(false, "文章不存在");
    }

    public String findAllArticle() {
        List<Article> articleList = articleRepository.findAll();
        return showData.showData(true, articleList.toString());
    }


    /**
     * 上传文章
     *
     * @param content
     * @return
     */
    private String uploadMarkDown(String content) {
        Timestamp time = new Timestamp(System.currentTimeMillis());
        String timeString = time.toString();
        timeString = timeString.split(" ")[0].split("-")[0] + timeString.split(" ")[0].split("-")[1] + timeString.split(" ")[0].split("-")[2] + timeString.split(" ")[1].split(":")[0] + timeString.split(" ")[1].split(":")[1] + timeString.split(" ")[1].split(":")[2].split("\\.")[0];
        String name = timeString + ".txt";
        MultipartFile file = strToFile(timeString, content);
        return uploadService.upload(file).get("fileName").toString();

    }

    /**
     * 字符串转文件
     *
     * @param title
     * @param content
     * @return
     */
    private MultipartFile strToFile(String title, String content) {
        try {
            final File htmlFile = File.createTempFile(title, ".txt");
            FileOutputStream fos = new FileOutputStream(htmlFile);
            try {
                PrintStream ps = new PrintStream(new FileOutputStream(htmlFile));
                ps.println(content);
                FileInputStream input = new FileInputStream(htmlFile);
                return new MockMultipartFile("file",
                        htmlFile.getName(), "text/plain", IOUtils.toByteArray(input));
            } finally {
                fos.flush();
                fos.close();
                htmlFile.deleteOnExit();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 文件转字符串
     *
     * @param url
     * @return
     * @throws IOException
     */
    private String sendGetData(String url) throws IOException {
        String result = "";
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(url);
        httpGet.addHeader("Content-type", "application/json");
        CloseableHttpResponse response = httpClient.execute(httpGet);
        if (response.getStatusLine().getStatusCode() == 200) {
            result = EntityUtils.toString(response.getEntity(), "utf-8");
        }
        response.close();
        return result;
    }

}
